//
//  KongWFindDoctorViewController.m
//  LoveOfPet
//
//  Created by dllo on 15/11/14.
//  Copyright © 2015年 孔维. All rights reserved.
//

#import "KongWFindDoctorViewController.h"
#import "KongWURLSessionHandle.h"
#import "KongWFindDoctorTableViewCell.h"
#import "KongWFindDoctorModel.h"
#import <MJRefresh.h>
#import "KongWAreaViewController.h"
#import "KongWFindDoctorDetailViewController.h"
#import <SVProgressHUD.h>
#define kHeight     [UIScreen mainScreen].bounds.size.height / 667
#define kWidth      [UIScreen mainScreen].bounds.size.width / 375
@interface KongWFindDoctorViewController ()<UITableViewDataSource, UITableViewDelegate, AreaDelegate>

@property (retain, nonatomic) UITableView *tableView;

@property (retain, nonatomic) NSMutableArray *modelArray;

@property (assign, nonatomic) NSInteger page;

@property (retain, nonatomic) NSMutableArray *doctorArray;

@property (copy, nonatomic) NSString *address;

@property (retain, nonatomic) MJRefreshAutoGifFooter *footer;

@property (retain, nonatomic) UIAlertView *alert;

@property (retain, nonatomic) UIButton *area;

@property (retain, nonatomic) UIButton *kindOfJob;

@property (retain, nonatomic) UIView *kindOfJobView;

@property (retain, nonatomic) UITableView *kindTable;

@property (retain, nonatomic) UIButton *recommend;

@property (retain, nonatomic) UIView *recommendView;

@property (retain, nonatomic) UITableView *recommendTable;

@property (retain, nonatomic) NSArray *kindArray;

@property (retain, nonatomic) NSArray *recommendArray;

@property (assign, nonatomic) NSInteger kindTag;

@property (assign, nonatomic) NSInteger recommendTag;

@end

@implementation KongWFindDoctorViewController
-(void)dealloc
{
    [_tableView release];
    [_modelArray release];
    [_address release];
    [_doctorArray release];
    [_footer release];
    [_alert release];
    [_kindOfJob release];
    [_area release];
    [_kindOfJobView release];
    [_kindTable release];
    [_kindArray release];
    [_recommend release];
    [_recommendView release];
    [_recommendTable release];
    [_recommendArray release];
    
    [super dealloc];

}
-(void)viewWillAppear:(BOOL)animated
{
    
    self.modelArray = [NSMutableArray array];
    self.doctorArray = [NSMutableArray array];
    [self backKindOfJobView];
    self.kindOfJob.selected = NO;
    [self backRecommendView];
    self.recommend.selected = NO;
    [self headerLoadNewData];
    self.footer.hidden = YES;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 0, 30, 30);
    self.title = @"找医生";
    [backBtn setBackgroundImage:[UIImage imageNamed:@"KongWback"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backBtnAction) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.kindTag = 0;
    self.recommendTag = 0;
    self.title = @"找医生";
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.page = 2;
    self.kindArray = @[@"全部", @"主治医师", @"主任医师", @"执业兽医师", @"执业助理兽医师"];
    self.recommendArray = @[@"智能推荐", @"距离最近", @"评价最高"];
    [self creatTableView];
    [self creatHeadView];
    
}

-(void)creatHeadView
{
    
    self.area = [UIButton buttonWithType:UIButtonTypeCustom];
    self.area.frame = CGRectMake(0, 64, (self.view.frame.size.width - kWidth * 2) / 3, kHeight * 30);
    [self.area setTitle:@"地区" forState:UIControlStateNormal];
    [self.area setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [self.area addTarget:self action:@selector(areaController) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:self.area];
    //分割线1
    UILabel *line1 = [[UILabel alloc] initWithFrame:CGRectMake((self.view.frame.size.width - kWidth * 2) / 3, self.area.frame.origin.y, kWidth * 1, self.area.frame.size.height)];
    line1.backgroundColor = [UIColor grayColor];
    [self.view addSubview:line1];
    [line1 release];
    
    self.kindOfJobView = [[UIView alloc] initWithFrame:CGRectMake(self.area.frame.origin.x + self.area.frame.size.width + 1, 64, (self.view.frame.size.width - kWidth * 2) / 3,  self.area.frame.size.height)];
    self.kindOfJobView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.kindOfJobView];
    [self.kindOfJobView release];
    
    
    self.kindOfJob = [UIButton buttonWithType:UIButtonTypeCustom];
    self.kindOfJob.frame = CGRectMake(self.area.frame.origin.x + self.area.frame.size.width + 1, 64, (self.view.frame.size.width - kWidth * 2) / 3,  self.area.frame.size.height);
    [self.kindOfJob setTitle:@"全部" forState:UIControlStateNormal];
    [self.kindOfJob setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [self.kindOfJob addTarget:self action:@selector(kindOfJob:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.kindOfJob];
    
    
    
    //分割线2
    UILabel *line2 = [[UILabel alloc] initWithFrame:CGRectMake(self.kindOfJob.frame.origin.x + self.kindOfJob.frame.size.width, self.kindOfJob.frame.origin.y, kWidth * 1, self.kindOfJob.frame.size.height)];
    line2.backgroundColor = [UIColor grayColor];
    [self.view addSubview:line2];
    [line2 release];
    self.recommendView = [[UIView alloc] initWithFrame:CGRectMake(((self.view.frame.size.width - kWidth * 2) / 3 + 1) * 2, 64, (self.view.frame.size.width - kWidth * 2) / 3, kHeight * 30)];
    self.recommendView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.recommendView];
    [self.recommendView release];
    
    self.recommend = [UIButton buttonWithType:UIButtonTypeCustom];
    self.recommend.frame = CGRectMake(self.kindOfJob.frame.origin.x + self.kindOfJob.frame.size.width + 1, 64, (self.view.frame.size.width - kWidth * 2) / 3, self.kindOfJob.frame.size.height);
    [self.recommend setTitle:@"智能推荐" forState:UIControlStateNormal];
    [self.recommend setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [self.recommend addTarget:self action:@selector(recommend:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.recommend];
    
    
    //分割线3
    UILabel *line3 = [[UILabel alloc] initWithFrame:CGRectMake(0, self.area.frame.origin.y + self.area.frame.size.height, self.view.frame.size.width, 1)];
    line3.backgroundColor = [UIColor grayColor];
    [self.view addSubview:line3];
    [line3 release];
  
}

-(void)creatKindTable
{
    self.kindTable = [[UITableView alloc] initWithFrame:self.kindOfJobView.bounds style:UITableViewStylePlain];
    
    self.kindTable.delegate = self;
    self.kindTable.dataSource = self;
    [self.kindTable registerClass:[UITableViewCell class] forCellReuseIdentifier:@"doctorKindTableCellIndentify"];
    [self.kindOfJobView addSubview:self.kindTable];
    [self.kindTable release];
}

-(void)creatRecommendTable
{
    self.recommendTable = [[UITableView alloc] initWithFrame:self.recommendView.bounds style:UITableViewStylePlain];
    
    self.recommendTable.delegate = self;
    self.recommendTable.dataSource = self;
    [self.recommendTable registerClass:[UITableViewCell class] forCellReuseIdentifier:@"doctorRecommendTableCellIndentify"];
    [self.recommendView addSubview:self.recommendTable];
    [self.recommendTable release];
}

-(void)creatTableView
{
   
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64 + kHeight * 31, self.view.frame.size.width, self.view.frame.size.height - 64) style:UITableViewStylePlain];
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[KongWFindDoctorTableViewCell class] forCellReuseIdentifier:@"findDoctorCellIndentify"];
    [self.view addSubview:self.tableView];
    [self.tableView release];
    
    //上拉刷新下拉加载
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerLoadNewData)];
    [self.tableView.header beginRefreshing];
    
    
    self.footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerLoadNewData)];
    [self.footer setTitle:@"玩命加载中......" forState:MJRefreshStateIdle];
    
    [self.footer beginRefreshing];
    self.tableView.footer = self.footer;
    
    
}

-(void)headerLoadNewData
{
    
    [KongWURLSessionHandle handleGETWithUrlString:[NSString stringWithFormat:@"http://api.5ichong.com/v1.2/doctor/find_doctor_with_list?longitude=4.9E-324&latitude=4.9E-324&job=%ld&sort=%ld&page=1&limit=20&city=%@", self.kindTag, self.recommendTag, self.address] parameters:nil showHuD:NO onView:nil successfulBlock:^(id responseObject) {
        NSDictionary *totalDic = responseObject;
        if (totalDic != nil) {
            if ([[[totalDic objectForKey:@"data"] objectForKey:@"list"] count] != 0) {
                for (NSDictionary *dic in [[totalDic objectForKey:@"data"] objectForKey:@"list"]) {
                    KongWFindDoctorModel *findDoctorModel = [KongWFindDoctorModel findDoctorWithDictionary:dic];
                    [self.modelArray addObject:findDoctorModel];
                }        self.doctorArray = [NSMutableArray arrayWithArray:[[totalDic objectForKey:@"data"] objectForKey:@"list"]];
                [self.tableView reloadData];
            }else
            {
                self.alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"暂时没有医生入驻" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
                [self.alert show];
                [self.alert release];
                NSTimer *timer;
                
                timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(doTime) userInfo:nil repeats:NO];
            }
           
      }
        
    } failureBlock:^(NSError *error) {
        NSLog(@"Error:%@", error);
    }];
    [self.tableView reloadData];
    [self.tableView.header endRefreshing];
    
    
}

-(void)footerLoadNewData
{
    
    [KongWURLSessionHandle handleGETWithUrlString:[NSString stringWithFormat:@"http://api.5ichong.com/v1.2/doctor/find_doctor_with_list?longitude=4.9E-324&latitude=4.9E-324&job=%ld&sort=%ld&page=%ld&limit=20&city=%@", self.kindTag, self.recommendTag, self.page, self.address] parameters:nil showHuD:NO onView:nil successfulBlock:^(id responseObject) {
        NSDictionary *totalDic = responseObject;
        if (totalDic != nil) {
            self.page ++;
            for (NSDictionary *dic in [[totalDic objectForKey:@"data"] objectForKey:@"list"]) {
                KongWFindDoctorModel *findDoctorModel = [KongWFindDoctorModel findDoctorWithDictionary:dic];
                [self.modelArray addObject:findDoctorModel];
                [self.doctorArray addObject:dic];
            }
            
        }
    } failureBlock:^(NSError *error) {
        NSLog(@"Error:%@", error);
    }];
    [self.tableView reloadData];
    [self.tableView.footer endRefreshing];
    
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.tableView) {
        return [self.doctorArray count];
    }else if (tableView == self.kindTable)
    {
        return self.kindArray.count;
    }else
    {
        return self.recommendArray.count;
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableView) {
        return kHeight * 170;
    }else if (tableView == self.kindTable)
    {
        return self.kindOfJobView.frame.size.height / 5;
    }else
    {
        return self.recommendView.frame.size.height / 3;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableView) {
        KongWFindDoctorTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"findDoctorCellIndentify"];
        cell.backgroundColor = [UIColor grayColor];
        if (self.modelArray.count != 0) {
            cell.findDoctorModel = [self.modelArray objectAtIndex:indexPath.row];
        }
        
        return cell;
    }else if (tableView == self.kindTable)
    {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"doctorKindTableCellIndentify"];
        cell.textLabel.text = self.kindArray[indexPath.row];
        return cell;
    }else
    {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"doctorRecommendTableCellIndentify"];
        cell.textLabel.text = self.recommendArray[indexPath.row];
        return cell;
    }
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableView) {
        KongWFindDoctorDetailViewController *findDoctorDetail = [[KongWFindDoctorDetailViewController alloc] init];
        findDoctorDetail.udid = ((KongWFindDoctorModel *)[self.modelArray objectAtIndex:indexPath.row]).uid;
        [findDoctorDetail setHidesBottomBarWhenPushed:YES];
        [self.navigationController pushViewController:findDoctorDetail animated:YES];
        [findDoctorDetail release];
    }else if (tableView == self.kindTable)
    {
        [self.kindOfJob setTitle:self.kindArray[indexPath.row] forState:UIControlStateNormal];
        self.kindTag = indexPath.row;
        [self.modelArray removeAllObjects];
        [self.doctorArray removeAllObjects];
        [self.tableView.header beginRefreshing];
        
        [self backKindOfJobView];
        self.kindOfJob.selected = NO;
    }else
    {
        [self.recommend setTitle:self.recommendArray[indexPath.row] forState:UIControlStateNormal];
        self.recommendTag = indexPath.row + 1;
        [self.modelArray removeAllObjects];
        [self.doctorArray removeAllObjects];
        [self.tableView.header beginRefreshing];
        [self backRecommendView];
        self.recommend.selected = NO;
    }
}

-(void)areaController
{
    [self.kindOfJob setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [self.recommend setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [self.area setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.area.backgroundColor = [UIColor colorWithRed:0.0806 green:0.3724 blue:0.9363 alpha:1.0];
    self.kindOfJob.backgroundColor = [UIColor whiteColor];
    self.recommend.backgroundColor = [UIColor whiteColor];
    KongWAreaViewController *area = [[KongWAreaViewController alloc] init];
    area.type = @"NO";
    area.delegate = self;
    [self.navigationController pushViewController:area animated:YES];
    [area release];
}

-(void)kindOfJob:(UIButton *)sender
{
    [self.recommend setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [self.area setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [sender setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    sender.backgroundColor = [UIColor colorWithRed:0.0806 green:0.3724 blue:0.9363 alpha:1.0];
    self.recommend.backgroundColor = [UIColor whiteColor];
    self.area.backgroundColor = [UIColor whiteColor];
    sender.selected = !sender.isSelected;
    
    if (sender.isSelected) {
        [self pushKindOfJobView];
        [self creatKindTable];
        [self backRecommendView];
        
        
    }else
    {
        [self backKindOfJobView];
        
    }
    self.recommend.selected = NO;
}
-(void)backBtnAction
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)recommend:(UIButton *)sender
{
    [self.kindOfJob setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [self.area setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [sender setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    sender.backgroundColor = [UIColor colorWithRed:0.0806 green:0.3724 blue:0.9363 alpha:1.0];
    self.kindOfJob.backgroundColor = [UIColor whiteColor];
    self.area.backgroundColor = [UIColor whiteColor];
     sender.selected = !sender.isSelected;
    if (sender.isSelected) {
        
        [self pushRecommendView];
        [self creatRecommendTable];
        [self backKindOfJobView];
        
    }else
    {
        [self backRecommendView];
        
    }
    self.kindOfJob.selected = NO;
}

#pragma mark 动画操作
-(void)pushKindOfJobView
{
    [UIView animateWithDuration:0.1 animations:^{
        self.kindOfJobView.frame = CGRectMake(0, 64 + kHeight * 31, self.view.frame.size.width, kHeight * 200);
    }];
}

-(void)backKindOfJobView
{
    [UIView animateWithDuration:0.1 animations:^{
        self.kindOfJobView.frame = CGRectMake((self.view.frame.size.width - kWidth * 2) / 3 + 1, 64, (self.view.frame.size.width - kWidth * 2) / 3,  kHeight * 30);
    }];
    self.kindTable.hidden = YES;

}

-(void)pushRecommendView
{
    [UIView animateWithDuration:0.1 animations:^{
        self.recommendView.frame = CGRectMake(0, 64 + kHeight * 31, self.view.frame.size.width, kHeight * 120);
    }];
}

-(void)backRecommendView
{
    [UIView animateWithDuration:0.1 animations:^{
        self.recommendView.frame = CGRectMake(((self.view.frame.size.width - kWidth * 2) / 3 + 1) * 2, 64, (self.view.frame.size.width - kWidth * 2) / 3, kHeight * 30);
    }];
    self.recommendTable.hidden = YES;
}
#pragma 代理方法
-(void)returnAreaName:(NSString *)str
{
    [self.area setTitle:str forState:UIControlStateNormal];
    self.address = str;

}

-(void)doTime
{
    //alert过1秒自动消失
    
    [self.alert dismissWithClickedButtonIndex:0 animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated{
    [SVProgressHUD dismiss];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
